<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    :title="isEdit ? '编辑物品' : '新增物品'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物品ID" prop="id" v-if="!isEdit">
            <el-input
              v-model="formData.id"
              placeholder="请输入物品ID"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物品类型" prop="category">
            <el-select
              v-model="formData.category"
              placeholder="请选择物品类型"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="category in categoryOptions"
                :key="category.key"
                :label="category.desc"
                :value="category.key"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="上架状态" prop="enable">
            <el-switch
              v-model="formData.enable"
              active-text="已上架"
              inactive-text="未上架"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">多语言名称</el-divider>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="中文名称" prop="name.zh">
            <el-input
              v-model="formData.name.zh"
              placeholder="请输入中文名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="英文名称" prop="name.en">
            <el-input
              v-model="formData.name.en"
              placeholder="请输入英文名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="阿语名称" prop="name.ar">
            <el-input
              v-model="formData.name.ar"
              placeholder="请输入阿语名称"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">图片资源</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="预览图片" prop="previewImageUrl">
            <el-input
              disabled
              v-model="formData.previewImageUrl"
              placeholder="请输入预览图片URL"
              clearable
            />
            <div class="image-preview">
              <Upload
                class="upload"
                v-if="currentCategoryFolder"
                :showFileList="false"
                :ossDir="currentCategoryFolder"
                accept=".jpg,.jpeg,.png"
                buttonText="上传物品"
                @upload-success="handleUploadSuccess"
              />

              <el-avatar
                :src="formData.previewImageUrl"
                :size="60"
                class="preview-avatar"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="动效图片" prop="animationImageUrl">
            <el-input
              disabled
              v-model="formData.animationImageUrl"
              placeholder="请输入动效图片URL"
              clearable
            />
            <div class="image-preview">
              <Upload
                class="upload"
                v-if="currentCategoryFolder"
                :showFileList="false"
                :ossDir="currentCategoryFolder"
                accept=".webp,.mp4,.vap,.svga,.pag,.gif,.apng"
                buttonText="上传动效"
                @upload-success="handleUploadSuccessAnimation"
              />
              <el-avatar
                :src="formData.animationImageUrl"
                :size="60"
                class="preview-avatar"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import Upload from "@/components/upload/OssUpload.vue";
import { OSS_DIR } from "@/api/oss";
import {
  addGoodApi,
  getGoodCategoriesApi,
  type GoodsDto,
  type GoodsCategoryRecord,
  type GoodInfo,
  updateGoodApi,
} from "@/api/good";

interface Props {
  modelValue: boolean;
  goodData?: GoodInfo | null;
  isEdit?: boolean;
}

interface Emits {
  (e: "update:modelValue", value: boolean): void;
  (e: "submit"): void;
}

const props = withDefaults(defineProps<Props>(), {
  goodData: null,
  isEdit: false,
});

const emit = defineEmits<Emits>();

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const formRef = ref<FormInstance>();
const categoryOptions = ref<GoodsCategoryRecord[]>([]);

// 表单数据
const formData = reactive<GoodsDto>({
  id: "",
  name: {
    zh: "",
    en: "",
    ar: "",
    text: "",
  },
  previewImageUrl: "",
  animationImageUrl: "",
  remark: "",
  category: "",
  subCategory: "",
  enable: false,
});

// 表单验证规则
const formRules: FormRules = {
  id: [
    { required: true, message: "请输入物品ID", trigger: "blur" },
    { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" },
  ],
  category: [{ required: true, message: "请选择物品类型", trigger: "change" }],
  "name.zh": [
    { required: true, message: "请输入中文名称", trigger: "blur" },
    {
      pattern: /^\S.*\S$|^\S$/,
      message: "名称前后不能有空格",
      trigger: "blur",
    },
  ],
  "name.en": [
    { required: true, message: "请输入英文名称", trigger: "blur" },
    {
      pattern: /^\S.*\S$|^\S$/,
      message: "名称前后不能有空格",
      trigger: "blur",
    },
  ],
  "name.ar": [
    { required: true, message: "请输入阿语名称", trigger: "blur" },
    {
      pattern: /^\S.*\S$|^\S$/,
      message: "名称前后不能有空格",
      trigger: "blur",
    },
  ],
  previewImageUrl: [
    { required: true, message: "请输入预览图片URL", trigger: "blur" },
    { type: "url", message: "请输入正确的URL格式", trigger: "blur" },
  ],
};

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      loadCategories();
      if (props.isEdit && props.goodData) {
        initFormData();
      } else {
        resetFormData();
      }
    }
  }
);

// 监听 visible 变化
watch(visible, (newVal) => {
  emit("update:modelValue", newVal);
});

// 计算当前选中分类的folder
const currentCategoryFolder = computed(() => {
  if (!formData.category) return "";
  const category = categoryOptions.value.find(
    (item) => item.key === formData.category
  );
  return category ? category.folder : "";
});

// 加载物品分类
const loadCategories = async () => {
  try {
    const response = await getGoodCategoriesApi();
    categoryOptions.value = response.data;
    console.log("物品分类:", response.data);
  } catch (error) {
    console.error("加载物品分类失败:", error);
  }
};

// 初始化表单数据（编辑模式）
const initFormData = () => {
  if (!props.goodData) return;

  Object.assign(formData, {
    id: props.goodData.id,
    name: { ...props.goodData.name },
    previewImageUrl: props.goodData.previewImageUrl,
    animationImageUrl: props.goodData.animationImageUrl,
    remark: props.goodData.remark,
    category: props.goodData.category,
    subCategory: props.goodData.subCategory,
    enable: props.goodData.enable,
  });
};

// 重置表单数据（新增模式）
const resetFormData = () => {
  Object.assign(formData, {
    id: "",
    name: {
      zh: "",
      en: "",
      ar: "",
      text: "",
    },
    previewImageUrl: "",
    animationImageUrl: "",
    remark: "",
    category: "",
    subCategory: "",
    enable: false,
  });
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
  formRef.value?.resetFields();
};

// 上传成功，保存到表单变量
const handleUploadSuccess = (file: any) => {
  formData.previewImageUrl = file;
};
const handleUploadSuccessAnimation = (file: any) => {
  formData.animationImageUrl = file;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    loading.value = true;

    // 更新 name.text 字段
    formData.name.text =
      formData.name.zh || formData.name.en || formData.name.ar;

    // 如果是编辑模式，需要包含ID
    const submitData = props.isEdit
      ? { ...formData, id: props.goodData?.id }
      : formData;
    if (props.isEdit) {
      await updateGoodApi(submitData);
    } else {
      await addGoodApi(submitData);
    }

    ElMessage.success(props.isEdit ? "更新成功" : "创建成功");
    emit("submit");
    handleClose();
  } catch (error) {
    if (error === false) {
      // 表单验证失败
      return;
    }
    console.error("提交失败:", error);
    ElMessage.error(props.isEdit ? "更新失败" : "创建失败");
  } finally {
    loading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  open: () => {
    visible.value = true;
  },
  close: handleClose,
});
</script>

<style scoped lang="less">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.image-preview {
  margin-top: 10px;

  .preview-avatar {
    border: 1px solid #e4e7ed;
    cursor: pointer;
    transition: transform 0.3s;

    &:hover {
      transform: scale(1.1);
    }
  }
}

.upload {
  margin-bottom: 10px;
}

:deep(.el-divider__text) {
  font-weight: bold;
  color: #409eff;
}
</style>
